<template>
  <div>
    <el-drawer
      ref="ruleDialog"
      :visible.sync="show"
      :title="form.id ? $t('setting.common.userCard.editHiddenUserInfo') : $t('setting.common.userCard.createHiddenUserInfo')"
      custom-class="rule-dialog"
      :wrapper-closable="false"
    >
      <div class="rule-dialog-content">
        <div class="rule-user-list-box">
          <p class="rule-user-list-box-title">{{$t('setting.common.userCard.title.selectPersonnelToHide')}}</p>
          <p class="rule-user-list-box-label" v-if="!isNotEmptySensitive">{{$t('setting.common.userCard.addDeptOrMember')}}</p>
          <div class="rule-user-list">
            <el-tag
              v-for="(item,index) in form.sensitiveMembers.departments"
              :key="item.deptId"
              closable
              type="info"
              @close="removeUser('sensitive','dept',index)">
              <i class="iconfont icon-bumen"></i>
              {{item.deptName}}
            </el-tag>
            <el-tag
              v-for="(item,index) in form.sensitiveMembers.staffList"
              :key="item.userId"
              closable
              type="info"
              @close="removeUser('sensitive','users',index)">
              <i class="iconfont icon-icon_people_fill"></i>
              {{item.staffName}}
            </el-tag>
          </div>
          <div><el-button type="text" icon="el-icon-plus" @click="chooseUser">{{isNotEmptySensitive ? $t('setting.common.userCard.continueAdd') : $t('common.base.add2')}}</el-button></div>

          <el-divider></el-divider>
          <p class="rule-user-list-box-title">{{$t('setting.common.userCard.title.selectHiddenFields')}}</p>
          <el-checkbox
            border
            v-for="item in detailList"
            :key="item.name"
            v-model="form.hideFields[item.name]">{{ item.label }}</el-checkbox>
        </div>
        <div class="rule-user-list-box">
          <p class="rule-user-list-box-title">{{$t('setting.common.userCard.title.selectWhiteList')}}</p>
          <p class="rule-user-list-box-label" v-if="!isNotEmptyWhite">{{$t('setting.common.userCard.setWhiteList')}}</p>
          <div class="rule-user-list">
            <el-tag
              v-for="(item,index) in form.whiteList.departments"
              :key="item.deptId"
              closable
              type="info"
              @close="removeUser('white','dept',index)">
              <i class="iconfont icon-bumen"></i>
              {{item.deptName}}
            </el-tag>
            <el-tag
              v-for="(item,index) in form.whiteList.staffList"
              :key="item.userId"
              closable
              type="info"
              @close="removeUser('white','users',index)">
              <i class="iconfont icon-icon_people_fill"></i>
              {{item.staffName}}
            </el-tag>
          </div>
          <div><el-button type="text" icon="el-icon-plus" @click="chooseWhiteList">{{isNotEmptyWhite ? $t('setting.common.userCard.continueAdd') : $t('common.base.add2')}}</el-button></div>
        </div>
      </div>
      <div class="rule-dialog-footer">
        <el-button @click="show = false">{{$t('common.base.close')}}</el-button>
        <el-button type="primary" @click="save" :loading="pending">{{$t('common.base.save')}}</el-button>
      </div>
    </el-drawer>
    
  </div>
</template>

<script>
import { t } from '@src/locales'
import * as UserCardApi from '@src/api/UserCard'

import { BaseSelectUserModeEnum } from '@src/component/common/BaseSelectUser'
/** mixin */
import { VersionControlOtherMixin } from '@src/mixins/versionControlMixin'

export default {
  name:'sensitive-rule-dialog',
  mixins: [VersionControlOtherMixin],
  props:{
    showCalendarSwitch:{
      type:Boolean,
      default:false
    }
  },
  computed:{
    isNotEmptySensitive(){
      return this.isNotEmptyUsers(this.form.sensitiveMembers)
    },
    isNotEmptyWhite(){
      return this.isNotEmptyUsers(this.form.whiteList)
    },
    isAllNotSelected(){
      let flag = true
      for(let key in this.form.hideFields){
        if(this.form.hideFields[key]){
          flag = false
        }
      }

      return flag
    },
    detailList(){
      let arr = [
        {label: t('common.fields.phone.displayName'), name: 'hidePhone'},
        {label: t('common.fields.email.displayName'), name: 'hideEmail'},
        {label: t('common.fields.department.displayName'), name: 'hideDepartment'},
        {label: t('common.fields.role.displayName'), name: 'hideRole'},
        {label: t('setting.common.userCard.displayName.calendar'), name: 'hideCalendar'},
        {label: t('setting.common.userCard.displayName.userDetail'), name: 'hideUserDetail'}
      ]
      if(!this._isShowEmail) {
        arr = arr.filter(item => item.name != 'hideEmail')
      }
      if(this.showCalendarSwitch) {
        return arr
      }
      return arr.filter(item => item.name != 'hideCalendar')
    }
  },
  data(){
    return {
      show:false,
      form:{
        sensitiveMembers:{
          departments:[],
          staffList:[]
        },
        hideFields:{
          hidePhone:false,
          hideEmail:false,
          hideDepartment:false,
          hideRole:false,
          hideCalendar:false,
          hideUserDetail:false
        },
        whiteList:{
          departments:[],
          staffList:[]
        }
      },
      pending:false
    }
  },
  methods:{
    open(form){
      this.show = true
      if(!form){
        return this.form = {
          sensitiveMembers:{
            departments:[],
            staffList:[]
          },
          hideFields:{
            hidePhone:false,
            hideEmail:false,
            hideDepartment:false,
            hideRole:false,
            hideCalendar:false,
            hideUserDetail:false
          },
          whiteList:{
            departments:[],
            staffList:[]
          }
        }
      }
      this.form = form
    },
    save(){
      if(!this.isNotEmptySensitive){
        return this.$platform.alert(t('setting.common.userCard.tip.tip1'))
      }
      if(this.isAllNotSelected){
        return this.$platform.alert(t('setting.common.userCard.tip.tip2'))
      }
      this.pending = true
      if(this.form.id){
        UserCardApi.updateUserCardRule(this.form).then(res=>{
          if(res.status == 0){
            this.show = false;
            this.$platform.toast(t('common.base.tip.modifySuccess'), 'success')
            this.$emit('ruleSuccess')
          }
        }).finally(()=>{
          this.pending = false
        })
      }else{
        UserCardApi.createUserCardRule(this.form).then(res=>{
          if(res.status == 0){
            this.show = false;
            this.$platform.toast(t('common.base.tip.createSuccess2'), 'success')
            this.$emit('ruleSuccess')
          }
        }).finally(()=>{
          this.pending = false
        })
      }

    },
    isNotEmptyUsers(val){
      return val && ((val.departments && val.departments.length > 0) || (val.staffList && val.staffList.length > 0))
    },
    chooseUser(){
      let selected = {
        depts:(this.form.sensitiveMembers?.departments || []).map(item=>{
          return {
            id: item.deptId,
            name: item.deptName
          }
        }),
        users:(this.form.sensitiveMembers?.staffList || []).map(item=>{
          return {
            userId:item.userId,
            staffId:item.staffId,
            head:item.head,
            displayName:item.staffName
          }
        }),
      }
      let options = {
        title: t('setting.common.userCard.selectHiddenUser'),
        unique:false,
        selectedUsers: selected.users,
        selectedDepartments: selected.depts,
        isCanChooseRole: false,
        mode: BaseSelectUserModeEnum.Filter
      };
      
      /** 
       * FIXME: 选人组件
      */
      return this.$fast.select.multi.all(options).then(result => {
        
        const depts = result.data.depts.concat(result.data.serviceProviders)
        
        if(result.status == 0) {
          this.form.sensitiveMembers = {
            departments: depts.map(item=>{
              return {
                deptId: item.id,
                deptName: item.name
              }
            }),
            staffList:(result.data.users || []).map(item=>{
              return {
                staffId:item.staffId,
                userId:item.userId,
                staffName:item.displayName,
                head:item.head
              }
            })
          }
        }
      }).catch(err => console.error(err))
    },
    chooseWhiteList(){
      let selected = {
        depts:(this.form.whiteList?.departments || []).map(item=>{
          return {
            id:item.deptId,
            name:item.deptName
          }
        }),
        users:(this.form.whiteList?.staffList || []).map(item=>{
          return {
            userId:item.userId,
            staffId:item.staffId,
            head:item.head,
            displayName:item.staffName
          }
        }),
      }
      let options = {
        title: t('setting.common.userCard.selectWhiteList'),
        selectedUsers: selected.users,
        selectedDepartments: selected.depts,
        unique: false,
        isCanChooseRole: false,
        mode: BaseSelectUserModeEnum.Filter
      };
      
      /** 
       * FIXME: 选人组件
      */
      return this.$fast.select.multi.all(options).then(result => {
        
        const depts = result.data.depts.concat(result.data.serviceProviders)
        
        if(result.status == 0) {
          this.form.whiteList = {
            departments: depts.map(item=>{
              return {
                deptId: item.id,
                deptName: item.name
              }
            }),
            staffList:(result.data.users || []).map(item=>{
              return {
                staffId:item.staffId,
                userId:item.userId,
                staffName:item.displayName,
                head:item.head
              }
            })
          }
        }
      }).catch(err => console.error(err))
    },
    removeUser(objType, type, index){
      if(objType == 'sensitive'){
        type == 'dept' ? this.form.sensitiveMembers.departments.splice(index, 1) : this.form.sensitiveMembers.staffList.splice(index, 1);
      }else{
        type == 'dept' ? this.form.whiteList.departments.splice(index, 1) : this.form.whiteList.staffList.splice(index, 1)
      }
    }
  }
}
</script>

<style lang='scss' scoped>
.choose-tag-user{
  line-height: 30px;
  padding:0 30px 0 10px;
  border: 1px solid rgb(224, 225, 226);
  border-radius: 3px;
  cursor: pointer;
  &:hover{
    border-color: $color-primary;
  }
  &.choose-null{
    color:#b2b2b2;
  }
}
</style>
<style lang="scss">
.rule-dialog {
  width:500px!important;
  .el-drawer__header{
    color:#171a1d;
  }
  .el-drawer__body{
    overflow-y:auto ;
  }
  .el-tag{
    margin-right: 12px;
  }
  .rule-dialog-content{
    min-height: 100%;
    overflow-y:auto;
    padding:20px;
    padding-bottom:60px;
    .rule-user-list-box{
      border: 1px solid hsla(210,7%,53%,.16);
      border-radius: 4px;
      padding: 24px;
      margin-bottom: 20px;
      &-label{
        color:rgba(23, 26, 29, 0.4);
      }
      &-title{
        color:#171a1d;
      }
      .el-checkbox.is-bordered{
        margin:0 20px 10px 0;
      }
    }
  }
  .rule-dialog-footer{
    border-top: 1px solid #f2f8f7;
    background-color:#fff;
    height: 60px;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    position: absolute;
    bottom:0;
    padding:0 20px;
  }
}
</style>